package com.apply.service.impl;


import com.alibaba.fastjson.JSON;
import com.apply.entity.Message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

       // import service.youandmeService;

@Service
public class WebSocketService implements WebSocketHandler{

   // @Autowired
   // private youandmeService youandmeService;

    //当MyWebSocketHandler类被加载时就会创建该Map，随类�?�?
    public static final Map<Integer, WebSocketSession> userSocketSessionMap;

    static {
        userSocketSessionMap = new HashMap<Integer, WebSocketSession>();
    }

    //握手实现连接
    public void afterConnectionEstablished(WebSocketSession webSocketSession){
    	
    	
    	
        try {
			int uid = (Integer) webSocketSession.getAttributes().get("uid");
			if (userSocketSessionMap.get(uid) == null) {

				userSocketSessionMap.put(uid, webSocketSession);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
    }

    //发送信息前的处理(服务器接收消息）
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage){

        try {
			if(webSocketMessage.getPayloadLength()==0)return;

      
			Message msg=JSON.parseObject(webSocketMessage.getPayload().toString(), Message.class);

			Timestamp now = new Timestamp(System.currentTimeMillis());
		} catch (Exception e) {
			
			
		}
      
       
    }

   
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable){

    }

    /**
     *连接关闭方法
     */
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus){

      
        try {
			Iterator<Map.Entry<Integer,WebSocketSession>> iterator = userSocketSessionMap.entrySet().iterator();
			
			while(iterator.hasNext()){
				
			    Map.Entry<Integer,WebSocketSession> entry = iterator.next();
			    
			    if(entry.getValue().getAttributes().get("uid")==webSocketSession.getAttributes().get("uid")){
			        userSocketSessionMap.remove(webSocketSession.getAttributes().get("uid"));
			       
			    }
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
    }

    
    public boolean supportsPartialMessages() {
        return false;
    }

    //发送信息的实现
    public void sendMessageToUser(int uid, TextMessage message)
            throws IOException {
        WebSocketSession session = userSocketSessionMap.get(uid);
        if (session != null && session.isOpen()) {
        	session.sendMessage(message);
        	
        }
    }
}